package com.qf.realm;

import com.qf.dao.UserPojoMapper;
import com.qf.pojo.UserPojo;
import com.qf.service.UsersService;
import com.qf.utils.PasswordUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UsersService usersService;
    //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken uToken = (UsernamePasswordToken) token;
        String username = uToken.getUsername();
        char[] password = uToken.getPassword();
        String pass = String.valueOf(password);
        String md5Pass = PasswordUtil.md5(pass,username,1024);
        System.out.println("realm======="+md5Pass);
        UserPojo login = usersService.login(username, md5Pass);
        if (login!=null){
            String realName = this.getName();
            ByteSource bytes = ByteSource.Util.bytes(username);
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, md5Pass, bytes, realName);
            return info;
        }else {
            throw new UnknownAccountException("用户名或密码错误");
        }
    }
    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();
        Set<String> roles = new HashSet<String>();
        if ("msj".equals(username)){
            roles.add("admin");
        }else {
            roles.add("admin2");
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        return info;
    }
}
